const query = require('module/mysql-pool'); // 数据库模块

const dao = {};

/**
 * 分页列表
 * @param {String} tableName 表格名称
 * @param {Object} params 参数
 * @param {String} whereStr 查询条件
 * @param {String} orderByStr 排序条件
 * @param {Function} callback 回调
 */
dao.getPageList = (tableName, params, whereStr, orderByStr, callback) => {
  // sql
  let countSql = 'SELECT COUNT(id) AS total FROM ' + tableName + whereStr;
  let querySql = 'SELECT * FROM ' + tableName + whereStr + orderByStr + ' LIMIT ?,?';
  // 分页步骤1-统计总条数
  query(countSql, null, (err, res) => {
    if (res) {
      let total = res[0].total;
      let pageNum = params.pageNum, pageSize = params.pageSize;
      // 分页步骤2-查询分页数据
      query(querySql, [pageNum * pageSize - pageSize, pageSize], (error, result) => {
        result.total = total;
        callback(error, result);
      });
    } else {
      callback(err, res);
    }
  });
}

/**
 * 详情
 * @param {String} tableName 表格名称
 * @param {String} id
 * @param {Function} callback 回调
 */
dao.detail = (tableName, id, callback) => {
  let sql = 'SELECT * FROM ?? WHERE id=?';
  query(sql, [tableName, id], (err, result) => {
    callback(err, result);
  });
}

/**
 * 新增
 * @param {String} tableName 表格名称
 * @param {Object} params 参数
 * @param {Function} callback 回调
 */
dao.add = (tableName, params, callback) => {
  let sql = 'INSERT INTO ?? SET ?';
  query(sql, [tableName, params], (err, result) => {
    callback(err, result);
  });
}

/**
 * 修改
 * @param {String} tableName 表格名称
 * @param {Object} params 参数
 * @param {Function} callback 回调
 */
dao.update = (tableName, params, callback) => {
  let sql = 'UPDATE ?? SET ? WHERE id=?';
  query(sql, [tableName, params, params.id], (err, result) => {
    callback(err, result);
  });
}

/**
 * 删除
 * @param {String} tableName 表格名称
 * @param {Array} ids id列表
 * @param {Function} callback 回调
 */
dao.remove = (tableName, ids, callback) => {
  let sql = 'DELETE FROM ?? WHERE';
  for (let id of ids) {
    sql += ' id=? OR';
  }
  sql = sql.slice(0, sql.length - 3);
  let parms = [...[tableName], ...ids];
  query(sql, parms, (err, result) => {
    callback(err, result);
  });
}

/**
 * 审核
 * @param {String} ids
 * @param {Function} callback 回调
 */
dao.audit = (tableName, params, callback) => {
  let sql = 'UPDATE ?? SET audit_state=? WHERE';
  for (let id of params.ids) {
    sql += ' id=? OR';
  }
  sql = sql.slice(0, sql.length - 3);
  let parms = [...[tableName], ...[params.audit_state], ...params.ids];
  query(sql, parms, (err, result) => {
    callback(err, result);
  });
}

module.exports = dao;